var User = (function () {
    var _user = {};
    //物流弹出层
    _user.logisDetail = function () {
        $('.see_logis').click(function () {
            $(this).siblings('.logis_detail').fadeIn();
        })
        $('.logis_close').click(function () {
            $(this).parent('.logis_detail').fadeOut();
        })
    }

    return _user;

})(jQuery, User)
var buy_order = {
    //结算页相关ajax的url
    URL: {
        province: function () {
            return global_ajaxdomain + 'getprovince.jhtm';
        },
        cities: function () {
            return global_ajaxdomain + 'getcities.jhtm';
        },
        counties: function () {
            return global_ajaxdomain + 'getcounties.jhtm';
        },
        villages: function () {
            return global_ajaxdomain + 'getvillages.jhtm?t=' + new Date().getTime();
        },
        zip: function () {
            return global_ajaxdomain + 'getzip.jhtm?t=' + new Date().getTime();
        },
        addconsignee: function () {
            return global_ajaxdomain + 'consignee/addconsignee.jhtm';
        },
        updateconsignee: function () {
            return global_ajaxdomain + 'consignee/updateconsignee.jhtm';
        },
        deleteconsignee: function () {
            return global_ajaxdomain + 'consignee/deleteconsignee.jhtm';
        }
    }
};
/*address enum*/
if (typeof AddressTypeEnums == 'undefined') {
    var AddressTypeEnums = {};
    AddressTypeEnums.DONGDE = "dongde";//懂得收货地址
    AddressTypeEnums.SH = "SH";//收货地址
    AddressTypeEnums.SP = "SP";//收票地址
    AddressTypeEnums.HT = "HT";//合同地址
}
// tab
function myTab(tabclass) {
    var tab_title = $(tabclass).find(".tab_title");
    var tab_body = $(tabclass).find(".tab_body");
    var tab_listIndex = 0;
    var _this = this;
    _this.tabclass = tabclass;
    tab_title.find(".tab_btn").click(function () {
        tab_listIndex = $(this).index();
        $(this).addClass("active").siblings().removeClass("active")
        tab_body.find(".tab_list").eq(tab_listIndex).show().siblings().hide();
    });
}

// 显示弹窗方法
function showLayer(addresstype) {
    if (addresstype == AddressTypeEnums.SH) {
        $('#h3').html("增加收货地址");
    } else if (addresstype == AddressTypeEnums.SP) {
        $('#h3').html("增加收票地址");
    }
    $('.zhezhao').fadeIn();
    var urlp = '/getprovince.jhtm';
    $.ajax({
        type: "get",
        url: urlp,
        async: false,
        dataType: "json",
        success: function (data) {
            if (data != null) {
                if (data.provinces != null) {

                    for (var i = 0; i < data.provinces.split(',').length; i++) {
                        var option = "<option >" + data.provinces.split(',')[i] + "</option>";
                        $("#goodsProvince").append(option);
                    }
                }
            }
        }
    });
    $("#isDefault").val("0");
    $('#insertAdd').fadeIn();
}
//隐藏弹窗方法
function hideLayer(layerclass) {
    $('.zhezhao').fadeOut();
    $(layerclass).fadeOut();
    $("#name").val("");
    $("#mobile").val("");
    $("#phone").val("");
    $("#goodsStreet").val("");
    $("#postcode").val("");
    $("#mail").val("");
    $("#flag1").val("0");
    $("#zip").val("");
    $("#company").val("");
    $("#goodsProvince").find("option").remove();
    $("#goodsProvince").append('<option value="">省份</option>');
    $("#goodsCity").find("option").remove();
    $("#goodsCity").append('<option value="">城市</option>');
    $("#goodsCounty").find("option").remove();
    $("#goodsCounty").append('<option value="">区县</option>');
    if ($("#goodsVillage")) {
        $("#goodsVillage").find("option").remove();
        $("#goodsVillage").append('<option value="">乡镇</option>');
    }
}
/*sh render provice city county*/
function renderArea(deliverprovice, delivercity, delivercounty, village) {
    $.ajax({
        type: "get",
        url: buy_order.URL.province(),
        async: false,
        dataType: "json",
        success: function (data) {
            if (data != null) {
                if (data.provinces != null) {

                    for (var i = 0; i < data.provinces.split(',').length; i++) {
                        var option = "<option >" + data.provinces.split(',')[i] + "</option>";
                        $("#goodsProvince").append(option);

                    }
                    var count = $("#goodsProvince option").length;
                    for (var i = 0; i < count; i++) {
                        if ($("#goodsProvince ").get(0).options[i].text == deliverprovice) {
                            $("#goodsProvince ").get(0).options[i].selected = true;
                            break;
                        }
                    }
                    var province = $("#goodsProvince").find("option:selected").text();
                    if (province != "") {
                        $.ajax({
                            type: "get",
                            url: buy_order.URL.cities(),
                            async: false,
                            data: {provincename: encodeURIComponent(province, "utf-8")},
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {
                                    if (data.cities != null) {
                                        $("#goodsCity").find("option").remove();
                                        for (var i = 0; i < data.cities.split(',').length; i++) {
                                            var option = "<option>" + data.cities.split(',')[i] + "</option>";
                                            $("#goodsCity").append(option);
                                        }
                                    }
                                    count = $("#goodsCity option").length;
                                    for (var i = 0; i < count; i++) {
                                        if ($("#goodsCity ").get(0).options[i].text == delivercity) {
                                            $("#goodsCity ").get(0).options[i].selected = true;
                                            break;
                                        }
                                    }
                                    var city = $("#goodsCity").find("option:selected").text();
                                    if (city != "") {
                                        $.ajax({
                                            type: "get",
                                            url: buy_order.URL.counties(),
                                            async: false,
                                            data: {
                                                provincename: encodeURIComponent(province, "utf-8"),
                                                cityname: encodeURIComponent(city, "utf-8")
                                            },
                                            dataType: "json",
                                            success: function (data) {
                                                if (data != null) {
                                                    if (data.counties != null) {
                                                        $("#goodsCounty").find("option").remove();
                                                        for (var i = 0; i < data.counties.split(',').length; i++) {
                                                            var option = "<option>" + data.counties.split(',')[i] + "</option>";
                                                            $("#goodsCounty").append(option);
                                                        }
                                                        count = $("#goodsCounty option").length;
                                                        for (var i = 0; i < count; i++) {
                                                            if ($("#goodsCounty ").get(0).options[i].text == delivercounty) {
                                                                $("#goodsCounty ").get(0).options[i].selected = true;
                                                                break;
                                                            }
                                                        }
                                                        if (shopId == 8 || shopId == 9) {
                                                            var county = $("#goodsCounty").find("option:selected").text();
                                                            if (county != "") {
                                                                $.ajax({
                                                                    type: "get",
                                                                    url: buy_order.URL.villages(),
                                                                    async: false,
                                                                    data: {
                                                                        provincename: encodeURIComponent(province, "utf-8"),
                                                                        cityname: encodeURIComponent(city, "utf-8"),
                                                                        countryname: encodeURIComponent(county, "utf-8")
                                                                    },
                                                                    dataType: "json",
                                                                    success: function (data) {
                                                                        if (data != null) {
                                                                            if (data.district != null) {
                                                                                $("#goodsVillage").find("option").remove();
                                                                                for (var i = 0; i < data.district.split(',').length; i++) {
                                                                                    var option = "<option>" + data.district.split(',')[i] + "</option>";
                                                                                    $("#goodsVillage").append(option);
                                                                                }
                                                                                count = $("#goodsVillage option").length;
                                                                                for (var i = 0; i < count; i++) {
                                                                                    if ($("#goodsVillage").get(0).options[i].text == village) {
                                                                                        $("#goodsVillage").get(0).options[i].selected = true;
                                                                                        break;
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
    });
}

// 显示弹窗方法
function updateAddress(village, company, zip, deliverid, delivername, delivermobile, deliverprovice, delivercity, delivercounty, deliverStreet, mail, delivertele, isdefault, addresstype) {
    if (addresstype == AddressTypeEnums.SH) {
        $('#h3').html("编辑收货地址");
    } else if (addresstype == AddressTypeEnums.SP) {
        $('#h3').html("编辑收票地址");
    }
    $('.zhezhao').fadeIn();
    $("#flag1").val("1");
    renderArea(deliverprovice, delivercity, delivercounty, village);
    $("#deliveridupdate").val(deliverid);
    $("#name").val(delivername);
    $("#mobile").val(delivermobile);
    $("#goodsStreet").val(deliverStreet);
    if (mail == "null") {
        $("#mail").val("");
    } else {
        $("#mail").val(mail);
    }
    if (delivertele == "null") {
        $("#phone").val("");
    } else {
        $("#phone").val(delivertele);
    }
    $("#isDefault").val(isdefault);
    $('#insertAdd').fadeIn();

    if ($("#zip").val() != undefined) {
        $("#zip").val(zip);
    }
    if ($("#company").val() != undefined) {
        $("#company").val(company);
    }
}


function getCities() {
    var province = $("#goodsProvince").find("option:selected").text();
    if (province != "") {
        var urlp = '/getcities.jhtm';
        $.ajax({
            type: "get",
            url: urlp,
            async: false,
            data: {provincename: encodeURIComponent(province, "utf-8")},
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.cities != null) {
                        $("#goodsCity").find("option").remove();
                        var option = "<option>城市</option>";
                        $("#goodsCity").append(option);
                        $("#goodsCounty").find("option").remove();
                        option = "<option>区县</option>";
                        $("#goodsCounty").append(option);
                        for (var i = 0; i < data.cities.split(',').length; i++) {
                            option = "<option>" + data.cities.split(',')[i] + "</option>";
                            $("#goodsCity").append(option);
                        }
                    }
                }
            }
        });
    }
}

function getCounties() {

    var city = $("#goodsCity").find("option:selected").text();
    var province = $("#goodsProvince").find("option:selected").text();
    if (city != "") {
        var urlp = '/getcounties.jhtm';
        $.ajax({
            type: "get",
            url: urlp,
            async: false,
            data: {provincename: encodeURIComponent(province, "utf-8"), cityname: encodeURIComponent(city, "utf-8")},
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.counties != null) {
                        $("#goodsCounty").find("option").remove();
                        var option = "<option>区县</option>";
                        $("#goodsCounty").append(option);
                        for (var i = 0; i < data.counties.split(',').length; i++) {
                            var option = "<option>" + data.counties.split(',')[i] + "</option>";
                            $("#goodsCounty").append(option);
                        }
                    }
                }
            }
        });
        if (shopId == 8 || shopId == 9) {
            getZip(province, city)
        }
    }
}
/*get smb zip */
function getZip(province, city) {

    if (city != "") {
        $.ajax({
            type: "get",
            url: buy_order.URL.zip(),
            async: false,
            data: {provincename: encodeURIComponent(province, "utf-8"), cityname: encodeURIComponent(city, "utf-8")},
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.zip != null) {
                        $("#zip").val(data.zip);
                    }
                }
            }
        });
    }
}
function getVillages() {

    var province = $("#goodsProvince").find("option:selected").text();
    var city = $("#goodsCity").find("option:selected").text();
    var county = $("#goodsCounty").find("option:selected").text();
    if (county != "") {
        $.ajax({
            type: "get",
            url: buy_order.URL.villages(),
            async: false,
            data: {
                provincename: encodeURIComponent(province, "utf-8"),
                cityname: encodeURIComponent(city, "utf-8"),
                countryname: encodeURIComponent(county, "utf-8")
            },
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.district != null) {
                        $("#goodsVillage").find("option").remove();
                        var option = "<option>乡镇</option>";
                        $("#goodsVillage").append(option);
                        for (var i = 0; i < data.district.split(',').length; i++) {
                            var option = "<option>" + data.district.split(',')[i] + "</option>";
                            $("#goodsVillage").append(option);
                        }
                    }
                }
            }
        });
    }
}
function submitInfo(addresstype) {
    var type_name = "";
    var temp_value = null;
    if (addresstype == AddressTypeEnums.SH) {
        type_name = "收货"
    } else if (addresstype == AddressTypeEnums.SP) {
        type_name = "收票"
    }
    var goodsProvince = $("#goodsProvince").find("option:selected").text();
    var goodsCity = $("#goodsCity").find("option:selected").text();
    var goodsCounty = $("#goodsCounty").find("option:selected").text();
    var goodsVillage = $("#goodsVillage").find("option:selected").text();

    temp_value = $("#name").val();
    if (isEmpty(temp_value)) {
        alert('请输入' + type_name + '人姓名');
        return false;
    }
    if (getStringLengthForChinese(temp_value) > 20) {
        alert(type_name + '人姓名超过20字符');
        return false;
    }
    if (!is_forbid(temp_value)) {
        alert(type_name + '人姓名含有非法字符');
        return false;
    }
    /*  var containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);
     if (containSpecial.test($.trim($("#name").val()))) {
     alert("请输入正确" + type_name + "人姓名");
     return false;
     }*/

    temp_value = $("#company").val();
    if (temp_value != undefined && isEmpty(temp_value)) {
        alert("请您填写" + type_name + "公司");
        return false;
    }
    if (temp_value != undefined && !is_forbid(temp_value)) {
        alert(type_name + "公司含有非法字符");
        return false;
    }

    var phone = $("#phone").val();
    var mobile = $("#mobile").val();
    if (isEmpty(phone) && isEmpty(mobile)) {
        alert('请您填写' + type_name + '人手机号码或者固定电话');
        return false;
    }

    if (!isEmpty(mobile)) {
        var reg = /^1[3-9]\d{9}$/;
        if (!reg.test(mobile)) {
            alert('请输入正确的手机号码');
            return false;
        }
    }
    if (!isEmpty(phone)) {
        if (!is_forbid_new(phone)) {
            alert('固定电话号码中含有非法字符');
            return false;
        }
        if (!checkPhoneNew(mobile, phone)) {
            alert('请输入正确的固定电话，格式为:XXX(区号)-XXXXXXXX(电话号码)-XXX(分机号)');
            return false;
        }
    }
    if (goodsProvince == "省份" || goodsCity == "城市" || goodsCounty == "区/县") {
        alert("请选择正确的省份/城市/区县");
        return false;
    }
    if ((shopId == 8 || shopId == 9) && goodsVillage == "乡镇") {
        alert("请选择正确的乡镇");
        return false;
    }
    temp_value = $("#goodsStreet").val();
    if (isEmpty(temp_value)) {
        alert("请您填写详细地址");
        return false;
    }
    if (!is_forbid(temp_value)) {
        alert("详细地址中含有非法字符");
        return false;
    }
    if (temp_value.length > 250) {
        alert("详细地址过长");
        return false;
    }
    if ($("#zip").val() != undefined) {
        if ($.trim($("#zip").val()) == "") {
            alert("请您填写邮政编码");
            return false;
        } else if (!isNumber($("#zip").val()) || $.trim($("#zip").val()).length != 6) {
            alert("请您填写正确的邮政编码");
            return false;
        }
    }

    temp_value = $("#mail").val();
    if (temp_value != "" && !temp_value.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) {
        alert("邮箱格式不正确");
        return false;
    }
    if (temp_value.length > 100) {
        alert("邮箱长度不能大于100位");
        return false;
    }
    var name = $.trim($("#name").val());
    var mobile = $.trim($("#mobile").val());
    var goodsStreet = $.trim($("#goodsStreet").val());
    var mail = $.trim($("#mail").val());
    var flag = $.trim($("#flag1").val());
    var deliverid = $.trim($("#deliveridupdate").val());
    var isdefault = $("#isDefault").val();
    var zip = $.trim($("#zip").val());
    var company = $.trim($("#company").val());
    var urlp = '/consignee/addconsignee.jhtm';
    if (flag == 1) {
        urlp = '/consignee/updateconsignee.jhtm';
    }
    var ajaxdata = {
        type: addresstype,
        delivername:  CtoH(name),
        deliverprovice: goodsProvince,
        delivercity: goodsCity,
        delivercounty: goodsCounty,
        deliverStreet:  CtoH(goodsStreet),
        delivertele:  CtoH(phone),
        delivermobile:  CtoH(mobile),
        deliveremail:  CtoH(mail),
        isDefault: isdefault,
        deliverid: deliverid,
        zip: CtoH(zip),
        company:  CtoH(company),
        towerShip: goodsVillage
    };
    $.ajax({
        type: "post",
        url: urlp,
        async: false,
        data: ajaxdata,
        dataType: "json",
        success: function (data) {
            if (data != null) {
                if (data.rc != null && data.rc == "0") {
                    hideLayer();
                    window.location.reload();
                } else if (data.rc != "0") {
                    hideLayer('.layer');
                    showMessage(3000, data.msg);
                }
            }
        }
    });

}

function deleteAddress_(deliverid, addresstype) {
    opencover("删除操作", "确认删除吗？", "deleteAddress('" + deliverid + "','" + addresstype + "')");
}

function deleteAddress(deliverid, addresstype) {
    var urlp = '/consignee/deleteconsignee.jhtm';
    var ajaxdata = {deliverid: deliverid, type: addresstype};
    $.ajax({
        type: "post",
        url: urlp,
        async: false,
        data: ajaxdata,
        dataType: "json",
        success: function (data) {
            if (data != null) {
                if (data.rc == 0) {
                    window.location.reload();
                }
            }
        }
    });
}


function setDefault(id, addresstype) {
    var urlp = '/consignee/setDefault.jhtm';
    $.ajax({
        type: "post",
        url: urlp,
        async: false,
        data: {id: id, type: addresstype},
        dataType: "json",
        success: function (data) {
            if (data != null) {
                if (data.rc == 0) {
                    window.location.reload();
                }
            }
        }
    });
}

function toPage(num, max, addresstype) {
    var index = num;
    var urlp = '/consignee/validatePage.jhtm';
    if (num <= 0) {
        alert("前面没有那么多页面了");
        return false;
    }
    if (num == 10000) {
        index = $("#pageNum").val();
        if (index < 0) {
            alert("您输入的页数有误");
            return false;
        }
        if (index > max) {
            alert("后面没有那么多页面了");
            return false;
        }
        $.ajax({
            type: "post",
            url: urlp,
            async: false,
            data: {index: index},
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.msg == "success") {
                        window.location.href = '/consignee/getPageListByType.jhtm?pageNum=' + index + '&pageSize=2&type=' + addresstype;
                    }
                }
            }
        });
    } else {
        if (num > max) {
            alert("后面没有那么多页面了");
            return false;
        }
        $.ajax({
            type: "post",
            url: urlp,
            async: false,
            data: {index: num},
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    if (data.msg == "success") {
                        window.location.href = '/consignee/getPageListByType.jhtm?pageNum=' + num + '&pageSize=2&type=' + addresstype;
                    }
                }
            }
        });
    }
    if (index == 1) {
        $('.prev').addClass('disable').siblings().removeClass("disable");
    } else if (index == max) {
        $('.next').addClass('disable').siblings().removeClass("disable");
    }
}

//select
jQuery.fn.select = function (options) {
    return this.each(function () {
        var $this = $(this);
        var $shows = $this.find(".shows");
        var $selectOption = $this.find(".selectOption");
        var $el = $this.find("ul > li");

        $this.click(function (e) {
            $(this).toggleClass("zIndex");
            $(this).children("ul").toggleClass("dis");
            e.stopPropagation();
        });

        $el.bind("click", function () {
            var $this_ = $(this);
            $this_.parent().parent().find(".selectOption").text($this_.text());
        });

        $("body").bind("click", function () {
            $this.removeClass("zIndex");
            $this.find("ul").removeClass("dis");
        })

        //eahc End
    });
}

$(function () {

//    // leftbar
//    User.leftbar();

    // select
    $(".selectContainer").select();

    // tab
    var userTab = new myTab(".user_tab");

})
/*page_number js 展示 */
function page_number(index, num, totalCount, type) {
    var pageStr = '';
    if (num > 0) {
        pageStr = pageStr + '<ul class="clearfix" style="width: 100%;">' +
            '<li class="page_btn prev">' +
            '<a href="javascript:;" title="上一页" class="clearfix" onclick="toPage(' + (index - 1) + ',' + num + ',\'' + type + '\')"><i></i><span>上一页</span></a>' +
            '</li>';
        for (var i = 1; i <= num; i++) {
            if (i == index) {
                pageStr = pageStr + '<li class="page_num" onclick="toPage(' + i + ',' + num + ',\'' + type + '\')" ><a href="javascript:;" style="color:red">' + i + '</a></li>'
            } else {
                pageStr = pageStr + ' <li class="page_num" onclick="toPage(' + i + ',' + num + ',\'' + type + '\')" ><a href="javascript:;">' + i + '</a></li>'
            }
        }
        pageStr = pageStr + ' <li class="page_btn next">' +
            '<a href="javascript:;" title="下一页" class="clearfix" onclick="toPage(' + (index + 1) + ',' + num + ',\'' + type + '\')"><i></i><span>下一页</span></a>' +
            '</li>' +
            '<li class="page_total">共' + num + '页</li>' +
            '<li class="page_goto">到第<input type="text" value="' + index + '" id="pageNum"/>页</li>' +
            '<li class="page_sure"><input type="button" value="确定" onclick="toPage(10000,' + num + ',\'' + type + '\')"/></li>' +
            '</ul>';
    }
    $("#page_number").append(pageStr);
    if (index == 1) {
        $('.prev').addClass('disable').siblings().removeClass("disable");
    } else if (index == num) {
        $('.next').addClass('disable').siblings().removeClass("disable");
    }
}
function getStringLengthForChinese(val) {
    var str = new String(val);
    var bytesCount = 0;
    for (var i = 0, n = str.length; i < n; i++) {
        var c = str.charCodeAt(i);
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            bytesCount += 1;
        } else {
            bytesCount += 2;
        }
    }
    return bytesCount;
}